package com.okq.action;

import com.okq.action.base.BaseActionSupport;
import com.okq.entity.Dict;
import com.okq.entity.User;
import com.okq.service.IDictService;
import com.okq.service.ILogService;
import com.okq.util.BaseTool;
import com.okq.util.PublicClass;
import com.okq.util.TimeTool;
import com.okq.util.page.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述 : 数据字典action
 * 作者 : zdl
 * 日期 : 2017/7/11 14:42
 */
public class DictAction extends BaseActionSupport {
    private static final long serialVersionUID = -5590039719913567600L;
    /**
     * 数据字典接口
     */
    @Autowired
    private IDictService dictServiceImpl;
    /**
     * 系统日志接口
     */
    @Autowired
    private ILogService logServiceImpl;
    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(DictAction.class);

    /**
     * 分页开始条数
     */
    private int iDisplayStart;

    /**
     * 每页显示条数
     */
    private int iDisplayLength;

    private String id;
    private Dict dict;
    private String dictType;
    private String type;

    /**
     * 获取数据字典分页列表
     *
     * @return json
     */
    public String getDictList() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                if (iDisplayLength == 0) {
                    iDisplayLength = -1;
                }
                int pageNum = (int) (Math.ceil(iDisplayStart / iDisplayLength)) + 1;
                /* 分页信息 */
                Page<Dict> pageInfo = new Page<>(iDisplayLength);
                pageInfo.setPageNo(pageNum);
                pageInfo = dictServiceImpl.pageByDict(pageInfo, dict);
                int iTotalRecords = pageInfo.getTotalCount();
                int iTotalDisplayRecords = pageInfo.getTotalCount() < 0 ? 0 : pageInfo.getTotalCount();
                /* 得到结果 */
                List<Dict> dList = pageInfo.getResult();
                /* 封装list */
                List<Map<String, Object>> dictMapList = new ArrayList<>();
                if (dList != null && !dList.isEmpty() && dList.size() > 0) {
                    int i = (pageNum - 1) * iDisplayLength + 1;
                    for (Dict d : dList) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("no", i);// 序号
                        map.put("id", d.getId());
                        map.put("name", StringUtils.defaultString(d.getName(), ""));
                        map.put("value", d.getValue() != null ? d.getValue() : -1);
                        map.put("type", StringUtils.defaultString(d.getType(), ""));
                        map.put("remark", StringUtils.defaultString(d.getRemark(), ""));
                        map.put("createUserName", StringUtils.defaultString(d.getCreateUserName(), ""));
                        map.put("createTime", TimeTool.timestampToString(d.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                        dictMapList.add(map);
                        i++;
                    }
                }
                Map<String, Object> jsonMap = new HashMap<>();
                jsonMap.put("iTotalRecords", iTotalRecords);
                jsonMap.put("iTotalDisplayRecords", iTotalDisplayRecords);
                jsonMap.put("aaData", dictMapList);

                String json = BaseTool.toJson(jsonMap);
                out.print(json);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 删除
     *
     * @return 成功标识
     */
    public String deleteDict() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                Dict d = dictServiceImpl.getDictById(id);
                if (d != null) {
                    dictServiceImpl.deleteDict(d);
                    out.print(0);
                    //添加系统日志
                    String userName = loginUser.getUserName();
                    String nowTime = TimeTool.getNowTime();
                    String content = "用户：" + userName + "，于" + nowTime + " 删除数据字典：" + d.getName() + "！";
                    PublicClass.addLog(userName, loginUser.getLoginName(), "数据字典", 2, content, logServiceImpl);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 跳转到修改页面
     *
     * @return type
     */
    public String toUpdate() {
        try {
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                dict = dictServiceImpl.getDictById(id);
                if (dict != null && type.equals("update")) {
                    return "update";
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    /**
     * 保存
     *
     * @return 成功标识
     */
    public String saveDict() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && dict != null) {
                //数据字典类型
                String dictType = dict.getType();
                List<Dict> dList = new ArrayList<>();
                if (StringUtils.isNotBlank(dictType)) {
                    dList = dictServiceImpl.listDictByType(dictType);
                }
                String userName = loginUser.getUserName();
                if (StringUtils.isNotBlank(type) && type.equals("add")) {// 新增
                    boolean unique = validateUnique(dict.getName(), dict.getValue(), dList);
                    if (!unique) {
                        out.print("exist");
                        return null;
                    }
                    dict.setId(BaseTool.getPK());
                    if (StringUtils.isNotBlank(userName)) {
                        dict.setCreateUserId(loginUser.getId());
                        dict.setCreateUserName(userName);
                    }
                    dictServiceImpl.saveDict(dict);
                    out.print("success");
                    //添加系统日志
                    String nowTime = TimeTool.getNowTime();
                    String content = "用户：" + userName + "，于" + nowTime + " 添加数据字典：" + dict.getName() + "！";
                    PublicClass.addLog(userName, loginUser.getLoginName(), "数据字典", 2, content, logServiceImpl);
                } else if (StringUtils.isNotBlank(type) && type.equals("update")) {// 修改
                    Dict oldDict = dictServiceImpl.getDictById(dict.getId());
                    if (oldDict != null) {
                        String newName = dict.getName();
                        Integer newValue = dict.getValue();
                        String validateName = null;
                        Integer validateValue = null;
                        //名称和值改变时，要验证同一类型下唯一性
                        if (!newName.equals(oldDict.getName())) {
                            validateName = newName;
                        }
                        if (!newValue.equals(oldDict.getValue())) {
                            validateValue = newValue;
                        }
                        boolean unique = validateUnique(validateName, validateValue, dList);
                        if (!unique) {
                            out.print("exist");
                            return null;
                        }
                        oldDict.setName(newName);
                        oldDict.setValue(newValue);
                        oldDict.setType(dictType);
                        if (StringUtils.isNotBlank(userName)) {
                            oldDict.setUpdateUserId(loginUser.getId());
                            oldDict.setUpdateUserName(userName);
                        }
                        dictServiceImpl.updateDict(oldDict);
                        out.print("success");
                        //添加系统日志
                        String nowTime = TimeTool.getNowTime();
                        String content = "用户：" + userName + "，于" + nowTime + " 修改数据字典：" + dict.getName() + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "数据字典", 2, content, logServiceImpl);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 获取同一种类型数据字典集合
     *
     * @return json
     */
    public String getAllDict() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(dictType)) {
                List<Dict> dList = dictServiceImpl.listDictByType(dictType);
                String data = BaseTool.toJson(dList);
                out.print(data);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 验证同一种数据字典类型下名称和值得唯一性
     *
     * @param name  名称
     * @param value 值
     * @param list  同种类型下的数据字典集合
     * @return boolean
     */
    private boolean validateUnique(String name, Integer value, List list) {
        boolean unique = true;
        if (list != null && !list.isEmpty() && list.size() > 0) {
            for (Object obj : list) {
                Dict d = (Dict) obj;
                String beName = d.getName();
                Integer beValue = d.getValue();
                if (StringUtils.isNotBlank(name) && name.equals(beName)) {
                    unique = false;
                    break;
                }
                if (value != null && value.equals(beValue)) {
                    unique = false;
                    break;
                }
            }
        }
        return unique;
    }


    public int getIDisplayStart() {
        return iDisplayStart;
    }

    public void setIDisplayStart(int iDisplayStart) {
        this.iDisplayStart = iDisplayStart;
    }

    public int getIDisplayLength() {
        return iDisplayLength;
    }

    public void setIDisplayLength(int iDisplayLength) {
        this.iDisplayLength = iDisplayLength;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Dict getDict() {
        return dict;
    }

    public void setDict(Dict dict) {
        this.dict = dict;
    }

    public String getDictType() {
        return dictType;
    }

    public void setDictType(String dictType) {
        this.dictType = dictType;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}
